"""

    多线程只对阻塞I/O工作有意义，因为I/O会释放GIL

"""

# 使用多线程和asyncio进行哈希计算

import asyncio
import functools
import hashlib
import os
from concurrent.futures import ThreadPoolExecutor
import random
import string

from async_threading import async_timed


def random_password(length):
    ascii_lowercase = string.ascii_lowercase.encode()
    return b"".join(bytes(random.choice(ascii_lowercase)) for _ in range(length))


passwords = [random_password(10) for _ in range(10000)]


def hash(password):
    salt = os.urandom(16)
    return str(hashlib.scrypt(password, salt=salt, n=2048, p=1, r=8))


@async_timed()
async def main():
    loop = asyncio.get_running_loop()
    tasks = []

    with ThreadPoolExecutor() as pool:
        for password in passwords:
            tasks.append(loop.run_in_executor(pool, functools.partial(hash, password)))
        await asyncio.gather(*tasks)


asyncio.run(main())
